package com.jrx.anytxn.transaction.job.cmpsCrt.step;

import com.jrx.anytxn.common.exception.TxnRuntimeException;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.dto.customer.CustomerRes;
import com.jrx.anytxn.customer.entity.CmCustomerBankcardInfo;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.param.entity.PmPartnerInfo;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.mapper.ext.ExtPmPartnerInfoMapper;
import com.jrx.anytxn.param.service.product.IProductTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.bean.DebtBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanAccountInfo;
import com.jrx.anytxn.transaction.entity.BtGuaranteeList;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import com.jrx.anytxn.transaction.entity.TlPaymentMapping;
import com.jrx.anytxn.transaction.job.autoPayment.bean.PaymentLogBean;
import com.jrx.anytxn.transaction.job.autoPayment.step.AutoPaymentPreLoanProcessor;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanAccountInfoMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentMappingMapper;
import com.jrx.anytxn.transaction.service.IPaymentLogService;
import com.jrx.anytxn.transaction.service.impl.DebtCalculationServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class CmpsPaymentPreProcessor implements ItemProcessor<BtGuaranteeList, PaymentLogBean> {

    private Logger logger = LoggerFactory.getLogger(AutoPaymentPreLoanProcessor.class);

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IProductTableService productTableService;
    @Resource
    private ExtPmPartnerInfoMapper extPmPartnerInfoMapper;
    @Resource
    private ExtAmLoanAccountInfoMapper extAmLoanAccountInfoMapper;
    @Resource
    private ExtTlPaymentLogMapper extTlPaymentLogMapper;
    @Resource
    private ExtTlPaymentMappingMapper extTlPaymentMappingMapper;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private DebtCalculationServiceImpl debtCalculationService;
    @Autowired
    private IPaymentLogService paymentLogService;

    @Override
    public PaymentLogBean process(BtGuaranteeList btGuaranteeList) throws Exception {
        logger.info("代偿扣款准备处理开始，订单编号：{}",btGuaranteeList.getLoanId());
        //1 获取业务日期
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        Date businessDate = org.getNextProcessingDate();

        //2 根据产品ID查询产品信息
        PrProductTable product = productTableService.findProByProIdAndOrgId(btGuaranteeList.getProductId(),
                btGuaranteeList.getOrganizationId(),btGuaranteeList.getTenantId());
        if(StringUtils.isBlank(product.getPartnerId())){
            logger.error("代偿扣款准备JOB，产品未设置合作伙伴编号，产品ID{}",product.getProductId());
            throw new TxnRuntimeException("代偿扣款准备JOB，产品未设置合作伙伴编号，产品ID : " + product.getProductId());
        }

        //3 查询合作伙伴信息 获取代偿回购账户
        PmPartnerInfo pmPartnerInfo = extPmPartnerInfoMapper.selectByTenantIdAndPartnerId(
                product.getTenantId(),product.getPartnerId());
        CmCustomerBankcardInfo bankcardInfo = new CmCustomerBankcardInfo();
        bankcardInfo.setTenantId(product.getTenantId());
        bankcardInfo.setCardNumber(pmPartnerInfo.getGuaranteeAcct());
        bankcardInfo.setBankId(org.getOrganizationId());
        bankcardInfo.setBankName(org.getChineseName());
        bankcardInfo.setCardType(TransBizConstant.CARD_TYPE_0);


        //4 查询客户正常状态贷款账户列表
        List<String> statusList = Arrays.asList(TransBizConstant.LOAN_STATUS_2);
        AmLoanAccountInfo accountInfo =
                extAmLoanAccountInfoMapper.selectByLoanIdAndAccountStatus(btGuaranteeList.getLoanId(),btGuaranteeList.getCustomerId(),
                        btGuaranteeList.getTenantId(),statusList);
        if(null == accountInfo){
            logger.info("未获取到订单信息");
            return null;
        }

        List<AmLoanAccountInfo> newLoanAcctList = new ArrayList<>();
        newLoanAcctList.add(accountInfo);

        //5 查詢客戶下正在还款的订单
        List<String> sumStatusList = Arrays.asList(TransBizConstant.PAYMENT_LOG_SUM_STATUS_O,
                TransBizConstant.PAYMENT_LOG_SUM_STATUS_T, TransBizConstant.PAYMENT_LOG_SUM_STATUS_D);
        List<TlPaymentLog> tlPaymentLogList =
                extTlPaymentLogMapper.selectListBySumStatusForBatch(btGuaranteeList.getCustomerId(),
                        btGuaranteeList.getChannel(),sumStatusList);
        //还款流水不空 与订单匹配
        if(CollectionUtils.isNotEmpty(tlPaymentLogList)){
            List<String> seqNoList = tlPaymentLogList.stream().map(TlPaymentLog::getSeqNo).collect(Collectors.toList());
            //获取对应的订单信息
            List<String> loanIdList = extTlPaymentMappingMapper.selectBySeqNoListForBatch(seqNoList);
            //剔除正在还款中的数据
            newLoanAcctList.removeIf(amLoanAccountInfo -> loanIdList.contains(amLoanAccountInfo.getLoanId()));
        }
        //验证后的贷款列表不为空
        if(CollectionUtils.isEmpty(newLoanAcctList)){
            logger.info("订单列表为空");
            return null;
        }

        //6 查询客户信息
        CustomerRes customer = customerService.getCustomerByChannelAndCustomerIdAndTensnId(btGuaranteeList.getChannel(),
                btGuaranteeList.getCustomerId(),btGuaranteeList.getTenantId());

        //还款流水列表
        List<TlPaymentLog> savePaymentLogList = new ArrayList<>(newLoanAcctList.size());
        //还款流水与订单映射信息
        List<TlPaymentMapping> tlPaymentMappingList = new ArrayList<>(newLoanAcctList.size());

        //7 遍历订单计算欠款
        for (AmLoanAccountInfo amLoanAccountInfo : newLoanAcctList) {
            //计算欠款
            DebtBean debtBean = debtCalculationService.getBalance(amLoanAccountInfo,businessDate,true, null,null,
                    false);
            if(debtBean.getTotalAmount().compareTo(BigDecimal.ZERO)<1){
                continue;
            }
            //构建还款流水
            TlPaymentLog tlPaymentLog =
                    paymentLogService.buildTlPaymentLog(TransBizConstant.REPAYMENT_TYPE_CMPS,
                            bankcardInfo, customer, debtBean.getTotalAmount(), businessDate, product, null);
            savePaymentLogList.add(tlPaymentLog);

            //构建还款流水与订单映射
            TlPaymentMapping tlPaymentMapping = paymentLogService.buildTlPaymentMapping(amLoanAccountInfo.getCustomerId(),
                    tlPaymentLog.getSeqNo(),amLoanAccountInfo.getLoanId(),amLoanAccountInfo.getTenantId());
            tlPaymentMappingList.add(tlPaymentMapping);
        }

        //8 判断是否有还款流水
        if(CollectionUtils.isNotEmpty(savePaymentLogList)){//有还款流水 返回信息
            //还款流水信息
            PaymentLogBean paymentLogBean = new PaymentLogBean();
            paymentLogBean.setTlPaymentLogList(savePaymentLogList);
            paymentLogBean.setTlPaymentMappingList(tlPaymentMappingList);
            return paymentLogBean;
        }
        return null;
    }
}
